package org.finalministry.gui.action;

import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.finalministry.database.dao.DaoFactory;
import org.finalministry.gui.GuiMain;
import org.finalministry.gui.components.FinalministryTree;
import org.finalministry.gui.components.tree.CongregationTreeNode;
import org.finalministry.gui.components.tree.TerritoryTreeNode;
import org.finalministry.objects.Congregation;
import org.finalministry.objects.Territory;

public class LoadDataIntoTree extends GuiActionBase {

	private FinalministryTree tree;

	public LoadDataIntoTree(GuiMain guiMain) {
		super(guiMain);
	}

	public void setTree(FinalministryTree tree) {
		this.tree = tree;
	}

	@Override
	public void performAction() {

		if (tree == null) {
			tree = new FinalministryTree(getGuiMain());
		}

		DefaultMutableTreeNode top = new DefaultMutableTreeNode("Finalministry");
		DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
		DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

		root.setUserObject("Finalministry");
		root.removeAllChildren();

		insertCongregations(root);

		model.reload(root);
	}

	private void insertCongregations(DefaultMutableTreeNode root) {
		try {
			List<Congregation> congregations = DaoFactory.getInstance().getCongregationDAO().getAll();

			for (Congregation congregation : congregations) {
				CongregationTreeNode congregationNode = new CongregationTreeNode(congregation.getName());
				root.add(congregationNode);

				insertTerritories(congregationNode, congregation);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void insertTerritories(DefaultMutableTreeNode congregationNode, Congregation congregation) {

		try {
			List<Territory> territories = DaoFactory.getInstance().getTerritoryDAO().getAllByCongregationId(congregation.getId());

			System.out.println("Territories = " + territories.size());

			for (Territory territory : territories) {
				TerritoryTreeNode territoryNode = new TerritoryTreeNode(territory.getNumber() + " - " + territory.getCity());

				congregationNode.add(territoryNode);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
